<template>
  <div>
    <el-card class="box-card">
      <!-- 按钮区域 -->
      <el-button
        type="primary"
        icon="Plus"
        @click="(addProductDialogVisible = true) && resetDialogForm()"
      >
        添加品牌
      </el-button>
      <el-table
        :data="pageDataList"
        border
        stripe
        style="width: 100%; margin: 10px 0"
      >
        <el-table-column
          label="序号"
          width="80"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column
          prop="pName"
          label="品牌名称"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column label="品牌Logo" align="center">
          <template #="{ row }">
            <img
              :src="row.logoUrl"
              alt="还未上传图片"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #="{ row }">
            <el-button
              type="warning"
              icon="Edit"
              @click="handleEditProduct(row)"
            ></el-button>
            <el-popconfirm
              :title="`确定要删除${row.pName}吗?`"
              width="250px"
              icon="Delete"
              @confirm="handleDeleteProduct(row._id)"
            >
              <template #reference>
                <el-button type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="pageInfo.total"
        v-model:current-page="pageInfo.current"
        v-model:page-size="pageInfo.limit"
        :page-sizes="[3, 5, 10]"
        @current-change="getProductResult"
        @size-change="getProductResult"
      />
      <template #footer>Footer content</template>
    </el-card>

    <el-dialog
      v-model="addProductDialogVisible"
      :title="addProductDialogForm._id ? '修改品牌' : '添加品牌'"
      width="30%"
      :before-close="closeDialog"
    >
      <el-form
        label-width="80px"
        :model="addProductDialogForm"
        :rules="rules"
        status-icon
        ref="addProductDialogFormRef"
      >
        <el-form-item label="品牌名称" prop="pName">
          <el-input v-model="addProductDialogForm.pName"></el-input>
        </el-form-item>
        <el-form-item label="品牌logo" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:3000/api/product/upload"
            name="logo"
            :drag="true"
            :show-file-list="false"
            :before-upload="beforeLogoUpload"
            :on-success="handleLogoSuccess"
          >
            <img
              v-if="addProductDialogForm.logoUrl"
              :src="addProductDialogForm.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="addProductDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleAddProduct">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { getProduct, addProduct, deleteProduct } from '@/api/product/index'
import type { Product, ProductFormData } from '@/api/product/type'
import type { UploadProps } from 'element-plus'
import { Message } from '@/utils/message'

const pageInfo = reactive({
  total: 20,
  current: 1,
  limit: 3,
})

const addProductDialogFormRef = ref()

const validatePName = (_rule: any, value: string, callback: any) => {
  if (value.trim().length >= 2) {
    return callback()
  } else {
    return callback(new Error('品牌名称不能少于2个字符'))
  }
}

const validateLogoUrl = (_rule: any, value: string, callback: any) => {
  if (value) {
    return callback()
  }
  return callback(new Error('请上传品牌logo'))
}

const rules = {
  pName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatePName,
    },
  ],
  logoUrl: [
    {
      required: true,
      trigger: 'blur',
      validator: validateLogoUrl,
    },
  ],
}

let addProductDialogVisible = ref<boolean>(false)

const addProductDialogForm = reactive<ProductFormData>({
  pName: '',
  logoUrl: '',
  _id: undefined,
})

let pageDataList = ref<Product[]>([])

const getProductResult = async (
  pager: number = addProductDialogForm._id ? pageInfo.current : 1,
) => {
  pageInfo.current = pager
  const result = await getProduct({
    pageLimit: pageInfo.limit,
    pageNum: pageInfo.current,
  })
  if (result.code === 200) {
    pageInfo.total = result.data.total
    pageDataList.value = result.data.productList
  }
}

const beforeLogoUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 20) {
    return false
  }
  return true
}

const handleLogoSuccess: UploadProps['onSuccess'] = (response, _uploadFile) => {
  addProductDialogForm.logoUrl = response.data.url
  addProductDialogFormRef.value.clearValidate('logoUrl')
}

const handleAddProduct = async () => {
  addProductDialogFormRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      Message('error', '请检查表单是否填写正确', 2000)
      return
    }
    const result = await addProduct(addProductDialogForm)
    addProductDialogVisible.value = false
    if (result.code === 200) {
      Message('success', result.message, 2000)
      getProductResult()
      resetDialogForm()
    }
  })
}

const handleEditProduct = (product: Product) => {
  addProductDialogVisible.value = true
  addProductDialogFormRef.value.clearValidate()
  addProductDialogForm.pName = product.pName
  addProductDialogForm.logoUrl = product.logoUrl
  addProductDialogForm._id = product._id
}

const handleDeleteProduct = async (id: string) => {
  const result = await deleteProduct(id)
  if (result.code === 200) {
    Message('success', result.message, 2000)
    getProductResult(
      pageDataList.value.length > 1 ? pageInfo.current : pageInfo.current - 1,
    )
  }
}

const resetDialogForm = () => {
  addProductDialogForm._id = undefined
  addProductDialogForm.logoUrl = ''
  addProductDialogForm.pName = ''
}

const closeDialog = (done: () => void) => {
  addProductDialogFormRef.value.clearValidate()
  resetDialogForm()
  done()
}

onMounted(() => {
  getProductResult()
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
